package com.ytjj.qmyx.supplychain.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.enums.ExpressEnums;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.kuaidi100.sdk.response.QueryTrackResp;
import com.kuaidi100.sdk.utils.PropertiesReader;
import com.kuaidi100.sdk.utils.SignUtils;
import com.rabbitmq.tools.json.JSONUtil;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.configuration.LINKPlatformConfig;
import com.ytjj.qmyx.supplychain.common.configuration.LinkConfigObject;
import com.ytjj.qmyx.supplychain.common.constants.RedisConstants;
import com.ytjj.qmyx.supplychain.common.constants.RedisKeyUtils;
import com.ytjj.qmyx.supplychain.common.enums.AbroadOrderPushTypeEnum;
import com.ytjj.qmyx.supplychain.common.enums.LinkPlatformMethodEnum;
import com.ytjj.qmyx.supplychain.common.enums.NeedPhoneExpressEnum;
import com.ytjj.qmyx.supplychain.common.enums.OrderStatusEnums;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.ReturnOrderStatisticsResponse;
import com.ytjj.qmyx.supplychain.common.model.dto.ProductDto;
import com.ytjj.qmyx.supplychain.common.model.request.ReturnGoodsQueryRequest;
import com.ytjj.qmyx.supplychain.common.model.request.ReturnGoodsRequest;
import com.ytjj.qmyx.supplychain.common.model.request.ReturnOrderStatisticsRequest;
import com.ytjj.qmyx.supplychain.common.model.request.link.OrderCancelRequest;
import com.ytjj.qmyx.supplychain.common.model.request.link.afterSale.GlobalSaleOrderRefund;
import com.ytjj.qmyx.supplychain.common.model.request.link.afterSale.PackageItem;
import com.ytjj.qmyx.supplychain.common.model.response.*;
import com.ytjj.qmyx.supplychain.common.utils.DateUtil;
import com.ytjj.qmyx.supplychain.common.utils.RedisService;
import com.ytjj.qmyx.supplychain.common.utils.TokenUtil;
import com.ytjj.qmyx.supplychain.common.utils.feishu.FeiShuUtil;
import com.ytjj.qmyx.supplychain.mapper.*;
import com.ytjj.qmyx.supplychain.mapper.entity.*;
import jdk.nashorn.internal.ir.IfNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
@RefreshScope
public class ReturnGoodsService {
    @Resource
    private ReturnGoodsMapper returnGoodsMapper;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private BankerOrderMapper bankerOrderMapper;
    @Resource
    private BankerStoreAddressMapper bankerStoreAddressMapper;
    @Resource
    private BankerProductMapper bankerProductMapper;
    @Resource
    private BankerService bankerService;
    @Resource
    private BankerMapper bankerMapper;
    @Resource
    private LinkErpService linkErpService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;
    @Autowired
    private BankerOrderService bankerOrderService;
    @Resource
    private AbroadOrderRecordMapper abroadOrderRecordMapper;
    @Resource
    private ReturnGoodsStaticsMapper returnGoodsStaticsMapper;
    @Resource
    MqProducerService mqProducerService;
    @Resource
    private ShopInfoService shopInfoService;
    /**
     * 包含境外商品的供应商id
     */
    @Value("${abroad.order.bankers:}")
    private String abroadBankerIds;
    /**
     * 境外商品上传wms系统的供应商id
     */
    @Value("${abroad.wms.bankerIds:}")
    private String abroadWMSBankerIds;
    /**
     * 境外商品上传link系统的供应商信息配置类
     */
    @Resource
    private LINKPlatformConfig linkPlatformConfig;

    @Resource
    private OrdersPayMapper ordersPayMapper;

    @Resource
    ReturnGoodsService returnGoodsService;

    /**
     * 快递更新时间差值 30分钟
     */
    private static final long DIFFERENCE_VALUE = 1800L;

    public CommonPage<ReturnGoodsResponse> selectList(ReturnGoodsRequest request) {
        YxBanker bankerInfo = bankerService.getUserInfo();
        if (null == bankerInfo) {
            return CommonPage.restPage(new ArrayList<>());
        }
        request.setBankerId(bankerInfo.getId());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<ReturnGoodsResponse> pageList = returnGoodsMapper.selectList(request);
        return CommonPage.restPage(pageList);
    }

    public CommonPage<ReturnGoodsResponse> selectAllList(ReturnGoodsRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<ReturnGoodsResponse> list = returnGoodsMapper.selectAllList(request);
        CommonPage<ReturnGoodsResponse> pageList = CommonPage.restPage(list);
        if (CollectionUtils.isEmpty(list)){
            return pageList;
        }
        List<String> childOrderNoList = list.stream().map(ReturnGoodsResponse::getChildOrderNo).collect(Collectors.toList());
        Example example = new Example(YxBankerOrder.class);
        example.createCriteria().andIn("childOrderNo",childOrderNoList);
        List<YxBankerOrder> yxBankerOrders = bankerOrderMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(yxBankerOrders)){
            return pageList;
        }
        pageList.setList(list.stream().map(page ->{
            List<YxBankerOrder> collect = yxBankerOrders.stream().filter(item -> item.getChildOrderNo().equals(page.getChildOrderNo())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)){
                YxBankerOrder yxBankerOrder = collect.get(0);
                page.setDeliverStatus(yxBankerOrder.getOrderStatus());
                page.setSource(yxBankerOrder.getSource());
                page.setExpressNo(yxBankerOrder.getExpressNo());
            }

            if(org.apache.commons.lang3.StringUtils.isNotBlank(page.getChildOrderNo())) {
                String substring = page.getChildOrderNo().substring(0, 1);
                if (substring.equals("Q")){
                    page.setOrderSource("xxxxQ");
                }else if (substring.equals("MZ")){
                    page.setOrderSource("yxyx");
                }else if (substring.equals("P")){
                    page.setOrderSource("xxxxP");
                }else if (substring.equals("K")){
                    page.setOrderSource("xxxxK");
                }
            }
            if (9 == page.getStatus()){
                page.setRefundTime(page.getUpdateTime());
            }
            return page;
        }).collect(Collectors.toList()));
        return pageList;
    }

    public CommonResult getReturnGoodsDetailInfoByServiceNo(String serviceNo,String mergeNo) {
        Example example = new Example(YxReturnGoods.class);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(serviceNo)){
            example.createCriteria().andEqualTo("serviceNo", serviceNo);
        }else {
            example.createCriteria().andEqualTo("mergeNo", mergeNo);
        }
        YxReturnGoods returnGoods = returnGoodsMapper.selectOneByExample(example);
        if (null == returnGoods) {
            return CommonResult.failed("获取数据失败");
        }
        return getReturnGoodsDetailInfo(returnGoods.getId());
    }

    public CommonResult<ReturnGoodsDetail> getReturnGoodsDetailInfo(Integer id) {
        ReturnGoodsDetail returnGoodsDetail = new ReturnGoodsDetail();
        log.info("===id==={}", id);
        // 商品信息
        ReturnProductDetail productInfo = returnGoodsMapper.getProductInfo(id);
        log.info("===productId==={}", productInfo);
        BigDecimal specPrice = returnGoodsMapper.getSpecPrice(productInfo.getProductId(), productInfo.getSpec());
        productInfo.setPrice(null != specPrice ? specPrice : BigDecimal.valueOf(0));
        returnGoodsDetail.setReturnProductDetail(productInfo);

        // 物流信息
        ReturnOrdersDetail ordersInfo = returnGoodsMapper.getOrdersInfo(id);
        if (null != ordersInfo && StringUtil.isNotEmpty(ordersInfo.getChildOrderNo())) {
            ordersInfo.setOrderNo(ordersInfo.getChildOrderNo());
        }
        returnGoodsDetail.setReturnOrdersDetail(ordersInfo);

        // 服务信息
        // 服务信息
        ReturnServiceDetail serviceInfo = returnGoodsMapper.getServiceInfo(id);
        //退货凭证
        if (null != serviceInfo.getUsersRemarksImg()) {
            //判断是否为视频
            String[] suffixs = serviceInfo.getUsersRemarksImg().split("\\.");
            if (null != suffixs && suffixs.length > 1) {
                String suffix = suffixs[suffixs.length - 1];
                String s = "avi、mov、rmvb、rm、flv、mp4、3gp";
                boolean contains = s.contains(suffix);
                serviceInfo.setVideo(contains);
            }
        }
        returnGoodsDetail.setReturnServiceDetail(serviceInfo);

        // 返商信息
        ReturnBankerDetail bankerInfo = returnGoodsMapper.selectReturnGoodsBankerInfo(id);
        if (null != bankerInfo && !StringUtils.isEmpty(bankerInfo.getReturnExpressNo()) && 1 == bankerInfo.getBankerStatus()) {
            returnGoodsDetail.setExpressNoIsExist(true);
        } else {
            returnGoodsDetail.setExpressNoIsExist(false);
        }

        //判断供应商是否能审核
        Boolean auditFlag = false;
        if (bankerInfo.getAfterType().equals(1) && bankerInfo.getStatus().equals(1)) {
            auditFlag = true;
        } else if (bankerInfo.getAfterType().equals(2) && bankerInfo.getStatus().equals(3)) {
            auditFlag = true;
        }
        bankerInfo.setAuditFlag(auditFlag);

        returnGoodsDetail.setReturnBankerDetail(bankerInfo);

        YxBankerStoreAddress address = productService.getAddress(bankerInfo.getAddressId());
        if (null != address){
            BankerStoreAddressResponse bankerStoreAddressResponse = new BankerStoreAddressResponse();
            BeanUtils.copyProperties(address,bankerStoreAddressResponse);

            returnGoodsDetail.setYxBankerStoreAddress(bankerStoreAddressResponse);
        }

        // 上侧时间线
        returnGoodsDetail.setReturnGoodsTime(returnGoodsMapper.getExpressInfo(id));

        return CommonResult.success(returnGoodsDetail);
    }

    public CommonResult auditSuccess(Integer id) {
        YxReturnGoods returnGoods = returnGoodsMapper.selectById(id);
        if (returnGoods.getBankerStatus().compareTo(1) != 0) {
            throw new ApiException("该退货数据已审核，暂无法操作！");
        }
        //如果售后类型为1退款
        if (returnGoods.getAfterType() == 1) {
            if (null != returnGoods && returnGoods.getStatus().intValue() == 6) {
                throw new ApiException("用户已撤销");
            }
            //判断是否来自团购渠道的售后
            boolean mark = "T".equals(returnGoods.getServiceNo().substring(0, 1));
            if(mark){
                YxBankerOrder bankerOrder = bankerOrderService.selectByChildOrderNo(returnGoods.getChildOrderNo());
                if(bankerOrder == null){
                    throw new ApiException("供应商该订单不存在！");
                }
                if (!StringUtils.isEmpty(bankerOrder.getExpressNo())) {
                    throw new ApiException("该订单已发货，暂无法操作！");
                }
            }else{
                YxBankerOrder bankerOrder = bankerOrderService.selectByChildOrderNo(returnGoods.getChildOrderNo());
                if (!StringUtils.isEmpty(bankerOrder.getExpressNo())) {
                    throw new ApiException("该订单已发货，暂无法操作！");
                }
            }
            returnGoodsMapper.updateStatus(id);
            return CommonResult.success();
        } else if (returnGoods.getAfterType() == 2 && StringUtils.isEmpty(returnGoods.getReturnExpressNo())) {
            throw new ApiException("该商品未寄回，暂无法操作！");
        }
        if (null != returnGoods && !returnGoods.getStatus().equals(3)) {
            throw new ApiException("货物未接收，暂无法操作！");
        }
        returnGoodsMapper.auditSuccess(id);
        return CommonResult.success();
    }

    public CommonResult auditFail(Integer id, String bankerRemarks) {
        YxReturnGoods returnGoods = returnGoodsMapper.selectById(id);
        if (returnGoods.getBankerStatus().compareTo(1) != 0) {
            throw new ApiException("该退货数据已审核，暂无法操作！");
        }
        if (returnGoods.getAfterType() == 2 && StringUtils.isEmpty(returnGoods.getReturnExpressNo())) {
            throw new ApiException("该商品未寄回，暂无法操作！");
        } else if (returnGoods.getAfterType() == 1) {
            //售后类型为退款 供应商拒绝
            returnGoodsMapper.auditFailByAfterType(id, bankerRemarks);
            return CommonResult.success();
        }
        if (null != returnGoods && returnGoods.getAfterType() == 2 && !returnGoods.getStatus().equals(3)) {
            throw new ApiException("货物未接收，暂无法操作！");
        }
        returnGoodsMapper.auditFail(id, bankerRemarks);
        if (returnGoods.getAfterType() != 3) {
            //恢复原有的状态
            String orderInfoStatus = "";
            String serviceNo = returnGoods.getServiceNo();
            //判断是否来自团购渠道的售后
            boolean mark = "T".equals(serviceNo.substring(0, 1));
            if(mark){
                orderInfoStatus = redisService.get("return:good:tuan:orderInfoStatus" + returnGoods.getChildOrderNo());
            }else if("YB".equals(serviceNo.substring(0, 2))){
                orderInfoStatus =  redisService.get("return:good:orderInfoStatus" + returnGoods.getChildOrderNo());
            }else {
                orderInfoStatus =  redisService.get("return:good:orderInfoStatus" + returnGoods.getOrdersInfoId());
            }

            if (!StringUtils.isEmpty(orderInfoStatus)) {
                Example example = new Example(YxOrders.class);
                //团购自提订单
                if (!StringUtils.isEmpty(returnGoods.getMergeNo())){
                    example.createCriteria().andEqualTo("childOrderNo", returnGoods.getMergeNo());
                }else {
                    example.createCriteria().andEqualTo("orderInfoId", returnGoods.getOrdersInfoId());
                }

                List<YxOrders> ordersList = ordersMapper.selectByExample(example);
                if (!CollectionUtils.isEmpty(ordersList)) {
                    YxOrders orders = ordersList.get(0);
                    orders.setOrderStatus(Integer.parseInt(orderInfoStatus));
                    orderService.saveByPrimaryKeySelective(orders);
                    bankerOrderMapper.updateOrderInfoStatus(orders.getChildOrderNo(),orders.getOrderStatus());
                }
            }
        }
        return CommonResult.success();
    }

    public Integer updateAddressIdById(ProductDto productDto) {
        //查询该退货信息是否已导入退货快递单号
        YxReturnGoods response = returnGoodsMapper.selectById(productDto.getId());
        if (!StringUtils.isEmpty(response.getReturnExpressNo())) {
            throw new ApiException("用户已寄回,地址不能更改");
        }
        return returnGoodsMapper.updateAddressIdById(productDto.getId(), productDto.getAddressId());
    }

    /**
     * 退款中的订单(排除用户撤销的)
     *
     * @return
     */
    public List<String> returningOrderList(Integer bankerId) {
        List<String> returnGoodsOrder = returnGoodsMapper.returningOrderList(bankerId);
        if (!CollectionUtils.isEmpty(returnGoodsOrder)) {
            return returnGoodsOrder;
        }
        return Arrays.asList();
    }

    public int haveReturnGoodsRecord(Integer orderInfoId) {
        Integer num = returnGoodsMapper.haveReturnGoodsRecord(orderInfoId);
        if (null != num && num > 0) {
            return num;
        }
        Integer returnRegisterNum = returnGoodsMapper.haveReturnRegisterRecord(orderInfoId);
        return null == returnRegisterNum ? 0 : returnRegisterNum;
    }

    public List<YxReturnGoods> selectList(List<Integer> codesInteger) {
        List<YxReturnGoods> resultList = returnGoodsMapper.selectList2(codesInteger);
        return resultList;
    }

    @Transactional(rollbackFor = Exception.class)
    public CommonResult returnGoodsUpload(YxReturnGoods yxReturnGoods) {
        log.info("==========上传售后参数=======yxReturnGoods=========={}", yxReturnGoods);
        yxReturnGoods.setId(null);
        int insert = returnGoodsMapper.insertSelective(yxReturnGoods);
        //上传成功把order/bankerOrder订单状态改为售后订单
        Example example = new Example(YxOrders.class);
        example.createCriteria().andEqualTo("childOrderNo",yxReturnGoods.getChildOrderNo());
        List<YxOrders> yxOrdersList = ordersMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(yxOrdersList)) {
            YxOrders yxOrders = yxOrdersList.get(0);
            Integer originalStatus = yxOrders.getOrderStatus();
            if (yxOrders.getOrderStatus() != 6){
                YxOrders nowOrders = new YxOrders();
                nowOrders.setId(yxOrders.getId());
                nowOrders.setOrderStatus(6);
                ordersMapper.updateByPrimaryKeySelective(nowOrders);
            }
            YxBankerOrder yxBankerOrder = bankerOrderService.selectByChildOrderNo(yxOrders.getChildOrderNo());
            if (yxBankerOrder.getOrderInfoStatus() != 6){
                yxBankerOrder.setOrderInfoStatus(6);
                bankerOrderMapper.updateByPrimaryKeySelective(yxBankerOrder);
            }
            //redis保存订单的原状态
            redisService.set("return:good:orderInfoStatus" + yxReturnGoods.getChildOrderNo(),originalStatus.toString());
            redisService.expire("return:good:orderInfoStatus" + yxReturnGoods.getChildOrderNo(),3600 * 24 * 180);
        }
        return insert > 0 ? CommonResult.success("上传成功") : CommonResult.failed("上传失败");
    }

    /**
    * 团购渠道提交售后申请--团购渠道专用
    * @param yxReturnGoods:
    * @returns: com.ytjj.qmyx.supplychain.common.api.CommonResult
    * 
    */
    @Transactional(rollbackFor = Exception.class)
    public CommonResult returnGoodsUploadFromTuan(YxReturnGoods yxReturnGoods) {
        log.info("==========团购渠道上传售后参数=======yxReturnGoods=========={}", yxReturnGoods);
        yxReturnGoods.setId(null);
        int insert = returnGoodsMapper.insertSelective(yxReturnGoods);
        //上传成功,把[order/bankerOrder]订单状态改为售后订单
        YxOrders yxOrders = new YxOrders();
        //有合单号，则按合单号查询订单数据；否则按照子订单号查询数据
        if(!StringUtils.isEmpty(yxReturnGoods.getMergeNo())){
            yxOrders.setChildOrderNo(yxReturnGoods.getMergeNo());
        }else{
            yxOrders.setChildOrderNo(yxReturnGoods.getChildOrderNo());
        }
        List<YxOrders> yxOrdersList = ordersMapper.select(yxOrders);
        if (!CollectionUtils.isEmpty(yxOrdersList)) {
            YxOrders yxOrders1 = yxOrdersList.get(0);
            //redis记录团购渠道订单的原状态
            redisService.set("return:good:tuan:orderInfoStatus" + yxOrders.getChildOrderNo(),yxOrders1.getOrderStatus().toString());
            redisService.expire("return:good:tuan:orderInfoStatus" + yxOrders.getChildOrderNo(),3600 * 24 * 30);
            //没有合单号，直接修改订单状态；否则根据[1]修改订单状态
            if(StringUtils.isEmpty(yxReturnGoods.getMergeNo())){
                YxOrders nowOrders = new YxOrders();
                nowOrders.setId(yxOrders1.getId());
                nowOrders.setOrderStatus(6);
                ordersMapper.updateByPrimaryKeySelective(nowOrders);
                YxBankerOrder yxBankerOrder = bankerOrderService.selectByChildOrderNo(yxOrders1.getChildOrderNo());
                yxBankerOrder.setOrderInfoStatus(6);
                bankerOrderMapper.updateByPrimaryKeySelective(yxBankerOrder);
            }else{
                Example example = new Example(YxReturnGoods.class);
                example.createCriteria().andEqualTo("mergeNo",yxReturnGoods.getMergeNo()).andNotIn("status", Arrays.asList(5, 6, 7));
                List<YxReturnGoods> returnGoods = returnGoodsMapper.selectByExample(example);
                //正在进行售后的商品总数
                Integer sum = returnGoods.stream().filter(r -> r.getProductNum() != null).map(YxReturnGoods::getProductNum).reduce(0,Integer::sum);
                //[1] 如果合单中所有商品都在售后，则设置为售后订单
                if(yxOrders1.getProductSum().equals(sum)){
                    YxOrders nowOrders = new YxOrders();
                    nowOrders.setId(yxOrders1.getId());
                    nowOrders.setOrderStatus(6);
                    ordersMapper.updateByPrimaryKeySelective(nowOrders);
                    YxBankerOrder yxBankerOrder = bankerOrderService.selectByChildOrderNo(yxOrders1.getChildOrderNo());
                    yxBankerOrder.setOrderInfoStatus(6);
                    bankerOrderMapper.updateByPrimaryKeySelective(yxBankerOrder);
                }
            }
        }
        return insert > 0 ? CommonResult.success("上传成功") : CommonResult.failed("上传失败");
    }

    @Transactional(rollbackFor = Exception.class)
    public CommonResult updateReturnGoods(YxReturnGoods yxReturnGoods) {
        Example old_example = new Example(YxReturnGoods.class);
        old_example.createCriteria().andEqualTo("serviceNo", yxReturnGoods.getServiceNo());
        List<YxReturnGoods> oldReturnGoodsList = returnGoodsMapper.selectByExample(old_example);
        if (!CollectionUtils.isEmpty(oldReturnGoodsList)) {
            log.debug("===更新前：{}", JSONObject.toJSONString(oldReturnGoodsList.get(0)));
            YxReturnGoods oldReturnGoods = oldReturnGoodsList.get(0);
            //修改快递单号后更新物流信息
            if (!StringUtils.isEmpty(oldReturnGoods.getReturnExpressCompany()) && !StringUtils.isEmpty(oldReturnGoods.getReturnExpressNo())
                    && !StringUtils.isEmpty(yxReturnGoods.getReturnExpressCompany()) && !StringUtils.isEmpty(yxReturnGoods.getReturnExpressNo())
                    && (!oldReturnGoods.getReturnExpressCompany().equals(yxReturnGoods.getReturnExpressCompany()) || !oldReturnGoods.getReturnExpressNo().equals(yxReturnGoods.getReturnExpressNo()))) {
                QueryTrack queryTrack = new QueryTrack();
                QueryTrackReq queryTrackReq = new QueryTrackReq();
                QueryTrackParam queryTrackParam = new QueryTrackParam();
                //特殊快递公司手机号为必填参数
                if(null != NeedPhoneExpressEnum.getExpressName(yxReturnGoods.getReturnExpressCompany())){
                    queryTrackParam.setPhone(yxReturnGoods.getRelatedPhone());
                }
                queryTrackParam.setCom(yxReturnGoods.getReturnExpressCompany());
                queryTrackParam.setNum(yxReturnGoods.getReturnExpressNo());
                queryTrackReq.setParam(queryTrackParam);
                queryTrackReq.setCustomer(PropertiesReader.get("customer"));
                queryTrackReq.setSign(SignUtils.sign(new Gson().toJson(queryTrackParam) + PropertiesReader.get("key") + PropertiesReader.get("customer")));
                QueryTrackResp resp = queryTrack.queryTrack(queryTrackReq);
                if (null != resp && null != resp.getState()) {
                    String expressRecord = JSONObject.toJSONString(resp.getData());
                    String expressText = JSONObject.toJSONString(resp);
                    returnGoodsMapper.updateExpressRecord(yxReturnGoods.getServiceNo(),expressRecord,expressText);
                }
            }
        }
        int i = 0;
        //根据服务单号修改----------订单的状态不需要改变
        Example example = new Example(YxReturnGoods.class);
        example.createCriteria().andEqualTo("serviceNo", yxReturnGoods.getServiceNo());
        i = returnGoodsMapper.updateByExampleSelective(yxReturnGoods, example);
        if(i > 0){
            //团购的【快递到家】或者【销售渠道】的售后单
            if (StringUtils.isEmpty(yxReturnGoods.getMergeNo())){
                //修改订单状态回到原状态
                if (null != yxReturnGoods.getStatus() && (yxReturnGoods.getStatus() == 5 || yxReturnGoods.getStatus() == 6 || yxReturnGoods.getStatus() == 7)){
                    YxReturnGoods returnGoods = returnGoodsMapper.selectOneByExample(example);
                    String orderInfoStatus = "";
                    //来自团购渠道的售后
                    String serviceNo = yxReturnGoods.getServiceNo();
                    //"T"团购渠道
                    boolean mark = "T".equals(serviceNo.substring(0, 1));
                    if(mark){
                        orderInfoStatus = redisService.get("return:good:tuan:orderInfoStatus" + returnGoods.getChildOrderNo());
                    }else{
                        orderInfoStatus = redisService.get("return:good:orderInfoStatus" + returnGoods.getChildOrderNo());
                    }
                    if (!StringUtils.isEmpty(orderInfoStatus)){
                        Example OrdersExample = new Example(YxOrders.class);
                        OrdersExample.createCriteria().andEqualTo("childOrderNo",returnGoods.getChildOrderNo());
                        YxOrders yxOrders = ordersMapper.selectOneByExample(OrdersExample);
                        YxOrders nowOrders = new YxOrders();
                        nowOrders.setId(yxOrders.getId());
                        //如果缓存是售后中状态，不正确，需要修复
                        if ("6".equals(orderInfoStatus)) {
                            List<YxBankerOrder> yxBankerOrders = bankerOrderMapper.selectByChildOrderNo(Arrays.asList(returnGoods.getChildOrderNo()));
                            YxBankerOrder yxBankerOrder = yxBankerOrders.get(0);
                            if (!com.alibaba.excel.util.StringUtils.isEmpty(yxBankerOrder.getExpressNo()) && !com.alibaba.excel.util.StringUtils.isEmpty(yxBankerOrder.getExpressCode())) {
                                orderInfoStatus = OrderStatusEnums.DELIVERY.getStatus();
                            } else {
                                orderInfoStatus = OrderStatusEnums.WAIT_DELIVERY.getStatus();
                            }
                        }
                        nowOrders.setOrderStatus(Integer.valueOf(orderInfoStatus));
                        ordersMapper.updateByPrimaryKeySelective(nowOrders);
                        Integer integer = bankerOrderMapper.updateOrderInfoStatus(yxOrders.getChildOrderNo(), Integer.valueOf(orderInfoStatus));
                    }else {
                        FeiShuUtil.sendMsg("供应链订单回到原状态失败！，原状态不存在，" + returnGoods.getChildOrderNo());
                    }
                }
            }
            try {
                //销售端上传退回快递单号后,验证是否需要推到菜鸟-销售订单销退单下发
//                afterSaleToLink(yxReturnGoods);
            } catch (Exception e) {
                log.error("========销售端上传退回快递单号后,验证是否需要推到菜鸟-销售订单销退单下发 异常=======",e.getMessage());
            }
        }
        return i > 0 ? CommonResult.success() : CommonResult.failed();
    }

    public CommonResult updateReturnGoodsType(YxReturnGoods yxReturnGoods) {
        Example OrdersExample = new Example(YxOrders.class);
        OrdersExample.createCriteria().andEqualTo("childOrderNo",yxReturnGoods.getChildOrderNo());
        YxOrders yxOrders = ordersMapper.selectOneByExample(OrdersExample);
        if(yxOrders.getOrderStatus() != 6){
            throw new ApiException("订单状态已不是售后状态，无法继续修改售后类型");
        }
        //根据服务单号修改----------订单的状态不需要改变
        Example example = new Example(YxReturnGoods.class);
        example.createCriteria().andEqualTo("serviceNo", yxReturnGoods.getServiceNo());
        returnGoodsMapper.updateByExampleSelective(yxReturnGoods, example);
        return CommonResult.success();
    }

    /**
     * 用户上传退货快递单号后判断是否需要上传到菜鸟
     * @param yxReturnGoods
     */
    private void afterSaleToLink(YxReturnGoods yxReturnGoods){
        //1.1验证该供应商是否需要上传菜鸟erp
        YxBanker banker = bankerMapper.selectByPrimaryKey(yxReturnGoods.getBankerId());
        if (null == banker.getErpId() || 1 == banker.getErpId()){
            return;
        }
        LinkErpResponse linkErp = linkErpService.getByBankId(yxReturnGoods.getBankerId());
        if (null == linkErp){
            return;
        }
        //2.是否有推送过境外仓库记录
        Example example = new Example(YxAbroadOrderRecord.class);
        example.createCriteria()
                .andEqualTo("orderNo", yxReturnGoods.getChildOrderNo())
                .andEqualTo("type", AbroadOrderPushTypeEnum.ADD.getCode());
        YxAbroadOrderRecord abroadOrderRecord = abroadOrderRecordMapper.selectOneByExample(example);
        if (null == abroadOrderRecord) {
            //没有推送过 则直接返回true
            return;
        }

        List<YxBankerOrder> bankerOrders = bankerOrderMapper.selectByChildOrderNoList(Collections.singletonList(yxReturnGoods.getChildOrderNo()));
        if (CollectionUtils.isEmpty(bankerOrders)){
            return;
        }
        YxBankerOrder yxBankerOrder = bankerOrders.get(0);

        //上传的参数
        GlobalSaleOrderRefund request = new GlobalSaleOrderRefund();
        request.setRefundOrderId(yxReturnGoods.getServiceNo());
        request.setSrcOutOrderId(yxReturnGoods.getChildOrderNo());
        request.setUserId(Long.parseLong(linkErp.getOwnerUserId()));
        request.setMailNo(yxReturnGoods.getReturnExpressNo());
        request.setStoreCode(linkErp.getStoreCode());
        request.setDistributionCompanyName(yxReturnGoods.getReturnExpressCompany());

        PackageItem packageItem = new PackageItem();
        packageItem.setItemId(Long.valueOf(yxBankerOrder.getThreeSkuId()));
        packageItem.setItemName(yxBankerOrder.getProductName());
        packageItem.setQuantity(yxReturnGoods.getProductNum());

        List<PackageItem> packageItems = new ArrayList<>();
        packageItems.add(packageItem);

        request.setPackageItems(packageItems);

        String resp = orderService.LINK_Request(JSONObject.toJSONString(request),
                LinkPlatformMethodEnum.GLOBAL_SALE_ORDER_REFUND_NOTIFY.getCode(),
                linkErp.getCode(),
                linkErp.getSecretKey());
        log.info("===link GLOBAL_SALE_ORDER_REFUND_NOTIFY resp==={}", resp);
        if (resp.indexOf("derCo") > 0) {
            resp = resp.replaceAll("derCo", "");
        }
        Map<String, Object> resultMap = JSONObject.parseObject(resp, Map.class);
        String success = String.valueOf(resultMap.get("success"));
        if (!"true".equals(success)) {
            log.info("===abroad linkplatform is can't cancel order, reason==={}, {}", resultMap.get("errorCode"), resultMap.get("errorMsg"));
//            redisService.set("LINK:GLOBAL_SALE_ORDER_REFUND_NOTIFY_"+ yxReturnGoods.getServiceNo(), JSONObject.toJSONString(resultMap));
//            redisService.expire("LINK:GLOBAL_SALE_ORDER_REFUND_NOTIFY_"+ yxReturnGoods.getServiceNo(), 3600 * 24);

        }else {
            String refundOrderCode = String.valueOf(resultMap.get("refundOrderCode"));
            if (!StringUtils.isEmpty(refundOrderCode)){
                returnGoodsMapper.updateLinkServiceNo(refundOrderCode,yxReturnGoods.getServiceNo());
            }
        }
    }


    public List<YxReturnGoods> selectListByStatus(Integer status) {
        return returnGoodsMapper.selectListByStatus(status);
    }


    /**
     * 处理退货物流
     */
    public QueryTrackResp dealReturnTrack(YxReturnGoods item) {
        //记录已处理的物流
        QueryTrackResp resp = new QueryTrackResp();
        if (null == item.getExpressUpdateTime() || DateUtil.secondBetween(new Date(), item.getExpressUpdateTime()) >= DIFFERENCE_VALUE) {
            //过滤默认填充的物流单号
            if ("123456".equals(item.getReturnExpressNo())) {
                return null;
            }
            QueryTrack queryTrack = new QueryTrack();
            QueryTrackReq queryTrackReq = new QueryTrackReq();
            QueryTrackParam queryTrackParam = new QueryTrackParam();
            //特殊快递公司手机号为必填参数
            if (null != NeedPhoneExpressEnum.getExpressName(item.getReturnExpressCompany())) {
                queryTrackParam.setPhone(item.getRelatedPhone());
            }
            queryTrackParam.setCom(item.getReturnExpressCompany());
            queryTrackParam.setNum(item.getReturnExpressNo());
            queryTrackReq.setParam(queryTrackParam);
            queryTrackReq.setCustomer(PropertiesReader.get("customer"));
            queryTrackReq.setSign(SignUtils.sign(new Gson().toJson(queryTrackParam) + PropertiesReader.get("key") + PropertiesReader.get("customer")));
            resp = queryTrack.queryTrack(queryTrackReq);
            if (null != resp && null != resp.getState()) {
                YxReturnGoods newEntity = new YxReturnGoods();
                newEntity.setReturnExpressNo(item.getReturnExpressNo());
                newEntity.setReturnExpressCompany(item.getReturnExpressCompany());
                newEntity.setExpressUpdateTime(new Date());
                newEntity.setExpressRecord(JSONObject.toJSONString(resp.getData()));
                newEntity.setExpressText(JSONObject.toJSONString(resp));
                //退货快递已签收
                if (ExpressEnums.isCheck(resp.getState()) && item.getStatus() == 8) {
                    //校验寄回地址
                    String areaName = "";
                    // 防止最新的一条没有值地区值
                    for (QueryTrackData trackData : resp.getData()) {
                        areaName = trackData.getAreaName();
                        if (org.apache.commons.lang3.StringUtils.isNotEmpty(areaName)) {
                            break;
                        }
                    }
                    //最新的一条物流记录
                    QueryTrackData queryTrackData = resp.getData().get(0);
                    //退回的签收时间是否已超2天
                    long value = System.currentTimeMillis() - DateUtil.StrToTime(queryTrackData.getFtime()).getTime();
                    long valueHour = value / 1000 / 3600;
                    if (valueHour < 48) {
                        //签收时间小于2天，不进入待退款
                    }else if (org.apache.commons.lang3.StringUtils.isNotEmpty(areaName)) {
                        String[] split = areaName.split(",");
                        if (split.length >= 2) {
                            //物流的签收城市
                            String city = split[1];
                            //获取寄回地址
                            List<BankerStoreAddressResponse> bankerStoreAddressResponses = bankerStoreAddressMapper.selectByBankerId(null, item.getAddressId());
                            if (bankerStoreAddressResponses.size() > 0) {
                                //供应商售后地址的城市
                                String bankerReturnCity = bankerStoreAddressResponses.get(0).getCity();
                                if (city.contains(bankerReturnCity) || bankerReturnCity.contains(city)) {
                                    // 客服提出的需求：“寄回快递状态签收后，售后订单立即变成待退款(status=4)
                                    newEntity.setStatus(4);
                                    newEntity.setGetExpressTime(DateUtil.StrToTime(queryTrackData.getFtime()));
                                    newEntity.setServiceBeizhu("");
                                } else {
                                    //售后订单状态只停留在已寄回待处理 (status=3)
                                    newEntity.setStatus(3);
                                    newEntity.setGetExpressTime(DateUtil.StrToTime(queryTrackData.getFtime()));
                                    newEntity.setServiceBeizhu("寄回地址与售后地址不符！");
                                }
                            }
                        }
                    }
                }
                // 更新寄回中售后快递单信息
                returnGoodsService.updateExpressReceiveStatus(newEntity);
            }
        }else {
            resp = JSON.parseObject(item.getExpressText(),QueryTrackResp.class) ;
        }
        return resp;
    }

    public void repairToOriginalStatus(){
        List<YxReturnGoods> unrepairData = returnGoodsMapper.getUnrepairData();
        for (YxReturnGoods item : unrepairData) {
            boolean needRepair = false;
            Example example = new Example(YxReturnGoods.class);
            example.createCriteria().andEqualTo("childOrderNo",item.getChildOrderNo());
            List<YxReturnGoods> yxReturnGoods = returnGoodsMapper.selectByExample(example);
            if(yxReturnGoods.size() == 1){
                YxReturnGoods nowData = yxReturnGoods.get(0);
                needRepair = Arrays.asList(5, 6, 7).contains(nowData.getStatus());
            }else if(yxReturnGoods.size() > 1){
                Set<Integer> set1 = yxReturnGoods.stream().map(e -> e.getStatus()).collect(Collectors.toSet());
                HashSet<Integer> set2 = new HashSet<>(Arrays.asList(0, 1, 2, 3, 4, 8, 9));
                //如果售后订单中不存在正常状态（"5", "6", "7"），那就需要更改订单状态为原状态
                List<Integer> intersection = set1.stream().filter(set2::contains).collect(Collectors.toList());
                if(intersection.size() == 0){
                    needRepair = true;
                }
            }
            //修复主订单
            if(needRepair){
                String orderInfoStatus = redisService.get("return:good:orderInfoStatus" + item.getChildOrderNo());
                if (!StringUtils.isEmpty(orderInfoStatus)){
                    Example OrdersExample = new Example(YxOrders.class);
                    OrdersExample.createCriteria().andEqualTo("childOrderNo",item.getChildOrderNo());
                    YxOrders yxOrders = ordersMapper.selectOneByExample(OrdersExample);
                    YxOrders nowOrders = new YxOrders();
                    nowOrders.setId(yxOrders.getId());
                    //如果缓存是售后中状态，不正确，需要修复
                    if ("6".equals(orderInfoStatus)) {
                        List<YxBankerOrder> yxBankerOrders = bankerOrderMapper.selectByChildOrderNo(Arrays.asList(item.getChildOrderNo()));
                        YxBankerOrder yxBankerOrder = yxBankerOrders.get(0);
                        if (!com.alibaba.excel.util.StringUtils.isEmpty(yxBankerOrder.getExpressNo()) && !com.alibaba.excel.util.StringUtils.isEmpty(yxBankerOrder.getExpressCode())) {
                            orderInfoStatus = OrderStatusEnums.DELIVERY.getStatus();
                        } else {
                            orderInfoStatus = OrderStatusEnums.WAIT_DELIVERY.getStatus();
                        }
                    }
                    nowOrders.setOrderStatus(Integer.valueOf(orderInfoStatus));
                    ordersMapper.updateByPrimaryKeySelective(nowOrders);
                    bankerOrderMapper.updateOrderInfoStatus(yxOrders.getChildOrderNo(), Integer.valueOf(orderInfoStatus));
                    log.info("定时任务已修复订单回到原状态：" + item.getChildOrderNo());
                }else {
                    FeiShuUtil.sendMsg("定时任务修复失败状态的订单->回到原状态失败！，原状态redis不存在，" + item.getChildOrderNo());
                }
            }
        }
    }

    /**
     * 修改售后单状态
     * @return void
     */
    public void updateExpressReceiveStatus(YxReturnGoods yxReturnGoods) {
        returnGoodsMapper.updateExpressReceiveStatus(yxReturnGoods);
    }

    public List<YxReturnGoods> selectListByAfterTypeAndBankerStatus() {
        return returnGoodsMapper.selectListByAfterTypeAndBankerStatus();
    }

    public List<YxReturnGoods> selectByBankerNotApproved() {
        return returnGoodsMapper.selectByBankerNotApproved();
    }

    public void updateBankerStatusAuto(Integer id) {
        returnGoodsMapper.updateBankerStatusAuto(id);
    }

    public void updateBankerStatusAutoByBankerNotApproved(Integer id) {
        returnGoodsMapper.updateBankerStatusAutoByBankerNotApproved(id);
    }

    public void verifyBankerRece() {
        // 获取所有已签收快递，但供应商没有审核的数据
        List<ReturnBankerReceResponse> pageList = returnGoodsMapper.selectReceList();
        if (!CollectionUtils.isEmpty(pageList)) {
            for (ReturnBankerReceResponse rece : pageList) {
                if (null == rece.getGetExpressTime()) {
                    continue;
                }
                // 计算两个时间之间的差
                long different = System.currentTimeMillis() - rece.getGetExpressTime().getTime();

                long secondsTime = 1000;
                long minutesTime = secondsTime * 60;
                long hoursTime = minutesTime * 60;

                long getHoursDiff = different / hoursTime;

                // 退货商品的快递识别为已签收后24h,供应商还未进行任何审核操作
                // 默认将供应商审核状态改为审核通过
                if (getHoursDiff >= 24) {
                    returnGoodsMapper.updateBankerStatus(rece.getId(),3);
                }
            }
        }
    }

    /**
     * 查询售后订单信息
     *
     * @param request
     * @return
     */
    public List<ReturnGoodsQueryResponse> queryReturnGoods(ReturnGoodsQueryRequest request) {
        List<ReturnGoodsQueryResponse> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(request.getMergeNos())){
            request.getMergeNos().stream().forEach(mergeNo -> {//团购单
                Example example = new Example(YxReturnGoods.class);
                example.createCriteria().andEqualTo("shopId", request.getShopId()).andEqualTo("mergeNo", mergeNo);
                example.selectProperties("serviceNo", "bankerStatus", "bankerRemarks", "bankerApplyTime", "status", "getExpressTime","mergeNo","expressText");
                List<YxReturnGoods> returnGoodsList = returnGoodsMapper.selectByExample(example);
                returnGoodsList.stream().forEach(item -> {
                    ReturnGoodsQueryResponse response = new ReturnGoodsQueryResponse();
                    BeanUtils.copyProperties(item, response);
                    result.add(response);
                });
            });
        }else {
            request.getServiceNo().stream().forEach(serviceNo -> {
                Example example = new Example(YxReturnGoods.class);
                example.createCriteria().andEqualTo("shopId", request.getShopId()).andEqualTo("serviceNo", serviceNo);
                example.selectProperties("serviceNo", "bankerStatus", "bankerRemarks", "bankerApplyTime", "status", "getExpressTime","expressText","serviceBeizhu");
                List<YxReturnGoods> returnGoodsList = returnGoodsMapper.selectByExample(example);
                returnGoodsList.stream().forEach(item -> {
                    ReturnGoodsQueryResponse response = new ReturnGoodsQueryResponse();
                    BeanUtils.copyProperties(item, response);
                    result.add(response);
                });
            });

        }
        return result;
    }

    public List<BankerStoreAddressResponse> getReturnGoodAddress(Integer bankerId, Integer addressId) {
        Assert.notNull(bankerId, "供应商id不能为空！");
        List<BankerStoreAddressResponse> addresses = bankerStoreAddressMapper.selectByBankerId(bankerId, addressId);
        addresses.stream().forEach(item -> {
            String pcaAddress = item.getProvince() + item.getCity() + (null == item.getArea() ? "" : item.getArea()) + item.getAddress();
            item.setPCAaddress(pcaAddress);
        });
        return addresses;
    }

    public List<BankerStoreAddressResponse> getReturnGoodAddressList(String bankerIds) {
        ArrayList<String> bankerIdList = Lists.newArrayList(bankerIds.split(","));
        List<BankerStoreAddressResponse> addresses = bankerStoreAddressMapper.getReturnGoodAddressList(bankerIdList);
        return addresses;
    }



    public String insertAddress(YxBankerStoreAddress yxBankerStoreAddress) {

        Example example = new Example(YxBankerStoreAddress.class);
        example.createCriteria().andEqualTo("tel", yxBankerStoreAddress.getTel())
                .andEqualTo("name", yxBankerStoreAddress.getName())
                .andEqualTo("provinceId", yxBankerStoreAddress.getProvinceId())
                .andEqualTo("cityId", yxBankerStoreAddress.getCityId())
                .andEqualTo("areaId", yxBankerStoreAddress.getAreaId());
        example.setOrderByClause("id desc limit 1");
        List<YxBankerStoreAddress> addresses = bankerStoreAddressMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(addresses)) {
            bankerStoreAddressMapper.insertSelective(yxBankerStoreAddress);
            Example example1 = new Example(YxBankerStoreAddress.class);
            example1.createCriteria().andEqualTo("tel", yxBankerStoreAddress.getTel())
                    .andEqualTo("name", yxBankerStoreAddress.getName())
                    .andEqualTo("provinceId", yxBankerStoreAddress.getProvinceId())
                    .andEqualTo("cityId", yxBankerStoreAddress.getCityId())
                    .andEqualTo("areaId", yxBankerStoreAddress.getAreaId());
            example1.setOrderByClause("id desc limit 1");
            List<YxBankerStoreAddress> addresses1 = bankerStoreAddressMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(addresses1)) {
                return null;
            }
            return String.valueOf(addresses1.get(0).getId());
        }
        return String.valueOf(addresses.get(0).getId());
    }

    public CommonResult updateBankerProductAddressId(Integer bankerProductId, Integer addressId) {
        YxBankerProduct yxBankerProduct = new YxBankerProduct();
        yxBankerProduct.setId(bankerProductId);
        yxBankerProduct.setAddressId(addressId);
        bankerProductMapper.updateByPrimaryKeySelective(yxBankerProduct);
        return CommonResult.success();
    }

    /**
     * 供应链退货管理
     */
    public CommonPage selectReturnGoodsList(ReturnGoodsRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        if(!StringUtils.isEmpty(request.getChildOrderNo())){
            String[] split = request.getChildOrderNo().split(",");
            if(split.length > 1){
                request.setChildOrderNos(Arrays.asList(split));
                request.setChildOrderNo(null);
            }
        }
        List<ReturnGoodsResponse> list = returnGoodsMapper.selectReturnGoodsList(request);
        if (CollectionUtils.isEmpty(list)) {
            return CommonPage.restPage(list);
        }
        List<String> childOrderNoList = list.stream().filter(item -> item.getChildOrderNo() != null).map(ReturnGoodsResponse::getChildOrderNo).collect(Collectors.toList());
        //支付信息
        Example ordersPayExample = new Example(YxOrdersPay.class);
        ordersPayExample.createCriteria().andIn("childOrderNo", childOrderNoList);
        List<YxOrdersPay> yxOrdersPayList = ordersPayMapper.selectByExample(ordersPayExample);

        list.stream().forEach(item ->{
            //是否发货
            if (!com.alibaba.excel.util.StringUtils.isEmpty(item.getExpressNo())) {
                item.setDeliverStatus((byte) 1);
            } else {
                item.setDeliverStatus((byte) 0);
            }
            item.setRefundStatus(null != item.getRefundTime() ? "已退款" : "未退款");
            if (item.getShopId().contains("GUOB")) {
                item.setOrderSource("xxxx");
            } else if (item.getShopId().contains("JUMD")) {
                item.setOrderSource("xxxx");
            }else if (item.getShopId().contains("YQKJ")) {
                item.setOrderSource("xxxx");
            }else if (item.getShopId().contains("ZXLP")) {
                item.setOrderSource("xxxx");
            }else if (item.getShopId().contains("YGYX")) {
                item.setOrderSource("xxxx");
            }else if (item.getShopId().contains("YXHD")) {
                item.setOrderSource("xxxx");
            }else if (item.getShopId().contains("JCYX")) {
                item.setOrderSource("xxxx");
            }

            //显示收款公司
            String account = item.getAccount();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(account)){
                Map<String, String> accountMap = new HashMap<>();
                accountMap.put("xxx01@xxxx","xxxx");
           

                item.setPayingMerchantName(accountMap.get(account));
            }
        });
        return CommonPage.restPage(list);
    }

    public Integer deleteReturnGoods(String serviceNo, String mergeNo,String orderInfoStatus) {
        Example example = new Example(YxReturnGoods.class);
        example.createCriteria().andEqualTo("serviceNo",serviceNo);
        //如果传过来的订单状态不为空,修改订单状态
        if (org.apache.commons.lang3.StringUtils.isNotBlank(orderInfoStatus)){
            List<YxReturnGoods> yxReturnGoodsList = returnGoodsMapper.selectByExample(example);
            YxReturnGoods yxReturnGoods = yxReturnGoodsList.get(0);
            Example ordersExample = new Example(YxOrders.class);
            ordersExample.createCriteria().andEqualTo("childOrderNo", yxReturnGoods.getChildOrderNo());
            List<YxOrders> yxOrdersList = ordersMapper.selectByExample(ordersExample);
            if (!CollectionUtils.isEmpty(yxOrdersList)) {
                YxOrders yxOrders = yxOrdersList.get(0);
                if (yxOrders.getOrderStatus() == 6) {
                    YxOrders nowOrders = new YxOrders();
                    nowOrders.setId(yxOrders.getId());
                    nowOrders.setOrderStatus(Integer.valueOf(orderInfoStatus));
                    ordersMapper.updateByPrimaryKeySelective(nowOrders);
                    YxBankerOrder yxBankerOrder = bankerOrderService.selectByChildOrderNo(yxOrders.getChildOrderNo());
                    if (yxBankerOrder.getOrderInfoStatus() == 6) {
                        yxBankerOrder.setOrderInfoStatus(Integer.valueOf(orderInfoStatus));
                        bankerOrderMapper.updateByPrimaryKeySelective(yxBankerOrder);
                    }
                }
            }
        }
        return returnGoodsMapper.deleteByExample(example);
    }

    public Integer removeReturnGoods(String serviceNo, String mergeNo,String orderInfoStatus) {
        Example example = new Example(YxReturnGoods.class);
        example.createCriteria().andEqualTo("serviceNo",serviceNo);
        List<YxReturnGoods> yxReturnGoodsList = returnGoodsMapper.selectByExample(example);
        YxReturnGoods yxReturnGoods = yxReturnGoodsList.get(0);
        //如果传过来的订单状态不为空,修改订单状态
        if (org.apache.commons.lang3.StringUtils.isNotBlank(orderInfoStatus)){
            Example ordersExample = new Example(YxOrders.class);
            ordersExample.createCriteria().andEqualTo("childOrderNo", yxReturnGoods.getChildOrderNo());
            List<YxOrders> yxOrdersList = ordersMapper.selectByExample(ordersExample);
            if (!CollectionUtils.isEmpty(yxOrdersList)) {
                YxOrders yxOrders = yxOrdersList.get(0);
                if (yxOrders.getOrderStatus() == 6) {
                    YxOrders nowOrders = new YxOrders();
                    nowOrders.setId(yxOrders.getId());
                    nowOrders.setOrderStatus(Integer.valueOf(orderInfoStatus));
                    ordersMapper.updateByPrimaryKeySelective(nowOrders);
                    YxBankerOrder yxBankerOrder = bankerOrderService.selectByChildOrderNo(yxOrders.getChildOrderNo());
                    if (yxBankerOrder.getOrderInfoStatus() == 6) {
                        yxBankerOrder.setOrderInfoStatus(Integer.valueOf(orderInfoStatus));
                        bankerOrderMapper.updateByPrimaryKeySelective(yxBankerOrder);
                    }
                }
            }
        }
        yxReturnGoods.setStatus(6);
        return returnGoodsMapper.updateByPrimaryKeySelective(yxReturnGoods);
    }


    public void verifyReturnGoodsOrders() {
        List<String> childOrderNoList = returnGoodsMapper.selectByStatus();
        Example example = new Example(YxOrders.class);
        //查询正在进行售后但是订单状态不为6的订单
        example.createCriteria().andNotEqualTo("orderStatus",6).andIn("childOrderNo",childOrderNoList);
        List<YxOrders> yxOrdersList = ordersMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(yxOrdersList)){
            yxOrdersList.stream().forEach(item ->{
                ordersMapper.updateOrderStatus(item.getChildOrderNo(),6);
                bankerOrderMapper.updateOrderInfoStatus(item.getChildOrderNo(),6);
            });
        }
    }

    /**
     * 境外订单能否取消
     * link平台实现方式：直接调用取消订单接口，如果返回成功表示能够申请退款，否则不能退款
     * wms平台待实现
     * @param yxReturnGoods
     * @return true=能 false=不能
     */
    public boolean abroadOrderCancelCheck(YxReturnGoods yxReturnGoods) {
        log.info("===abroadOrderCancelCheck==={}", yxReturnGoods.getChildOrderNo());
        //1.1检查是否有境外供应商
        if (StringUtils.isEmpty(abroadBankerIds)) {
            log.info("===abroadBankerIds is null===");
            return true;
        }
        //1.2查询缓存中是否有记录过调用第三方校验平台, 并且第三方平台返回是失败的
        String key = RedisKeyUtils.ABROAD_ORDER_CANCELCHECK + yxReturnGoods.getChildOrderNo();
        String redisVal = redisService.get(key);
        if ("1".equals(redisVal)) {
            return false;
        }
        //2.是否有推送过境外仓库记录
        Example example = new Example(YxAbroadOrderRecord.class);
        example.createCriteria()
                .andEqualTo("orderNo", yxReturnGoods.getChildOrderNo())
                .andEqualTo("type", AbroadOrderPushTypeEnum.ADD.getCode());
        YxAbroadOrderRecord abroadOrderRecord = abroadOrderRecordMapper.selectOneByExample(example);
        if (null == abroadOrderRecord) {
            //没有推送过 则直接返回true
            return true;
        }
        //3.校验wms平台
        if ("WMS".equals(abroadOrderRecord.getServiceName())) {
            log.info("===order is wms platform===");
            List<String> wmsBankerIdsStr = Arrays.asList(abroadWMSBankerIds.split(","));
            List<Integer> wmsBankerIds = wmsBankerIdsStr.stream().map(Integer::parseInt).collect(Collectors.toList());
            // todo 是否能取消订单
            return true;
        }

        //4.校验link平台
        if ("LINK".equals(abroadOrderRecord.getServiceName())) {
            log.info("===order is link platform===");
            List<LinkConfigObject> linkBankerList = linkPlatformConfig.getLinks();
            /**
             * 正常情况下 link_object_matchs 肯定不会为空
             * 有没有一种情况，就是某家供应商突然不跟link平台合作了，而还有在途中的订单，
             * 导致程序这边删除了配置，从而这里程序出现异常
              */
            List<LinkConfigObject> link_object_matchs = linkBankerList.stream().filter(item
                    -> item.getBankerId().equals(yxReturnGoods.getBankerId())).collect(Collectors.toList());
            /**
             * 上面的特殊情况处理
             */
            if (CollectionUtils.isEmpty(link_object_matchs)) {
                log.info("===cancel order is exceptional case==={}", yxReturnGoods.getChildOrderNo());
                return true;
            }
            LinkConfigObject linkConfigObject = link_object_matchs.get(0);
            //是否能取消订单
            OrderCancelRequest request = OrderCancelRequest.builder()
                    .userId(Long.valueOf(linkConfigObject.getOwnerUserId()))
                    .externalOrderId(yxReturnGoods.getChildOrderNo())
                    .lgOrderCode(abroadOrderRecord.getLgOrderCode())
                    .orderSource(linkConfigObject.getOrderSource())
                    .build();
            String resp = orderService.LINK_Request(JSONObject.toJSONString(request),
                    LinkPlatformMethodEnum.CANCEL.getCode(),
                    linkConfigObject.getCode(),
                    linkConfigObject.getSecretKey());
            log.info("===link return goods resp==={}", resp);
            if (resp.indexOf("derCo") > 0) {
                resp = resp.replaceAll("derCo", "");
            }
            Map<String, Object> resultMap = JSONObject.parseObject(resp, Map.class);
            String success = String.valueOf(resultMap.get("success"));
            if (!"true".equals(success)) {
                log.info("===abroad linkplatform is can't cancel order, reason==={}, {}", resultMap.get("errorCode"), resultMap.get("errorMsg"));
                redisService.set(key, "1");
                //这里只缓存了一个小时，因为担心客户前一次申请是在快递途中，而后面收到货后要走退款操作导致这里的直接命中缓存时的拒绝
                redisService.expire(key, 3600);
                return false;
            }
        }
        return true;
    }

    /**
     * 统计退款订单
     */
    public void statisticsReturnOrder(String markId, List<ReturnOrderStatisticsResponse> orderStatisticsResponses){
        String key = RedisConstants.RETURN_GOOD_STATISTICS+markId;
        String s = redisService.get(key);
        String partentId = TokenUtil.getPartentId();
        YxShopInfo shopInfo = shopInfoService.queryShopInfoByPartnerId(partentId);
        try {
            String shopId = null == shopInfo ? "" : shopInfo.getShopId();
            if (!StringUtils.isEmpty(s)) {
                if(!CollectionUtils.isEmpty(orderStatisticsResponses)){
                    returnGoodsStaticsMapper.batchInsert(markId,shopId,orderStatisticsResponses);
                }
                redisService.decrement(key, 1);
            }
        } catch (Exception e) {
            log.error(shopInfo.getShopId() + "执行单品退单统计出错！{}" + e);
            returnGoodsStaticsMapper.markFinished(markId,2);
        } finally {
            String valueStr = redisService.get(key);
            if (!StringUtils.isEmpty(valueStr)) {
                Integer value = Integer.valueOf(valueStr);
                if (value <= 0) {
                    returnGoodsStaticsMapper.markFinished(markId,1);
                    redisService.remove(key);
                }
            }
        }
    }

    /**
     * 统计单品售后
     */
    public Integer doProductRefundStatistics(ReturnOrderStatisticsRequest orderStatisticsResponses){
        return mqProducerService.doProductRefundStatistics(orderStatisticsResponses);
    }

    /**
     * 分页查询单品统计详情
     */
    public CommonPage<ReturnGoodStatisticsDetail> getProductRefundStatisticsDetail(String markId,Integer pageNum,Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<ReturnGoodStatisticsDetail> statisticsReturnDetail = returnGoodsStaticsMapper.getProductRefundStatisticsDetail(markId);
        return CommonPage.restPage(statisticsReturnDetail);
    }

    /**
     * 分页查询单品统计详情-汇总
     */
    public ReturnGoodStatisticsDetail getProductRefundStatisticsSummary(String markId){
        ReturnGoodStatisticsDetail statisticsReturnDetail = returnGoodsStaticsMapper.getProductRefundStatisticsSummary(markId);
        return statisticsReturnDetail;
    }


    /**
     * 查询退款订单的统计历史
     */
    public CommonPage<ReturnGoodStatisticsSearch> getHistoryProductRefund(Integer pageNum,Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<ReturnGoodStatisticsSearch> ReturnGoodStatisticsSearch = returnGoodsStaticsMapper.getHistoryProductRefund();
        return CommonPage.restPage(ReturnGoodStatisticsSearch);
    }

}
